package cn.kent.controller;

import cn.kent.controller.vo.R;
import cn.kent.controller.vo.response.FileRes;
import cn.kent.service.FileService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author SunChenpeng
 * @date 2021/11/22 17:36
 */
@Controller
public class FileController {
    private final static Logger LOG = LoggerFactory.getLogger(FileController.class);

    private FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    /**
     * 展示文件上传页面
     *
     * @param model
     * @return
     */
    @GetMapping("file-upload")
    public ModelAndView fileUpload(Model model) {
        ModelAndView mv = new ModelAndView("file-upload");
        return mv;
    }

    /**
     * 上传文件
     *
     * @param file    文件
     * @param request 请求
     * @return 视图
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public ModelAndView uploadFile(@RequestParam(value = "file") MultipartFile file,
                                   HttpServletRequest request) {
        LOG.info("开始上传文件");
        ModelAndView mv = new ModelAndView("file-ok");
        ModelMap modelMap = new ModelMap();
        FileRes fileRes = null;
        try {
            fileRes = fileService.uploadFile(file);
            modelMap.addAttribute("msg", "上传成功");
            modelMap.addAttribute("fileName", fileRes.getFileName());
            modelMap.addAttribute("path", fileRes.getPath());
            modelMap.addAttribute("url", fileRes.getUrl());
            mv.addAllObjects(modelMap);
        } catch (IOException e) {
            modelMap.addAttribute("msg", "上传失败");
            mv.addAllObjects(modelMap);
        } finally {
            LOG.info("结束上传文件" + JSON.toJSONString(fileRes));
        }
        return mv;
    }

    @RequestMapping(value = "file-list", method = RequestMethod.GET)
    public ModelAndView list(Model model) {
        ModelAndView mv = new ModelAndView("file-list");
        List<FileRes> fileList = fileService.getFileList();
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("fileList", fileList);
        mv.addAllObjects(modelMap);
        return mv;
    }

}
